<template>
  <div>
    <h1>实验模块</h1>

    <el-tabs v-model="activeName">
      <el-tab-pane label="数据获取" name="first">
        <el-form :inline="true" :model="DataAccessSearch">
          <el-form-item label="实验编号">
            <el-input v-model="DataAccessSearch.ExpId" placeholder="请填写实验编号"></el-input>
          </el-form-item>
          <el-form-item label="功能单元编号">
            <el-input v-model="DataAccessSearch.UnitId" placeholder="请填写实验名称"></el-input>
          </el-form-item>
          <el-form-item label="功能单元名称">
            <el-input v-model="DataAccessSearch.UnitName" placeholder="请填写功能单元名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-switch v-model="DataAccessSearch.StateIf" active-text="仅显示完成实验" inactive-text=""></el-switch>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" icon="el-icon-search">查询</el-button>
          </el-form-item>
        </el-form>
        <el-table
            :data="tableData"
            height="500"
            border
            style="width: 100%"
            :header-cell-style="{textAlign: 'center'}"
            :cell-style="{ textAlign: 'center' }"
            :row-class-name="tableRowClassName">
          <el-table-column
              prop="labid"
              sortable
              label="实验编号"
              width="240">
          </el-table-column>
          <el-table-column
              prop="procedureid"
              sortable
              label="功能单元编号"
              width="240">
          </el-table-column>
          <el-table-column
              prop="procedurename"
              sortable
              label="功能单元名称"
              width="240">
          </el-table-column>
          <el-table-column
              prop="procedurestate"
              sortable
              label="功能单元状态"
              width="240">
          </el-table-column>
          <el-table-column
              label="操作"
              width="240">
            <template #default="scope">
              <el-button @click="handleClick(scope.row)" el-button type="info" plain>获取数据</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="进行实验" name="second">
        <div style="position: fixed; top: 0px; right:0px; color:black">
          <el-button type="primary" icon="el-icon-refresh" size='mini' @click="setTime()"></el-button>
          <span class="el-icon-time"> 距离预约结束还有{{ timeDay }}分{{ timeer }}秒</span>
        </div>
        <div class="block">
          <el-image :src="src"></el-image>
        </div>
      </el-tab-pane>

      <el-tab-pane label="状态反馈" name="third">
        <center>
          <div style="max-width: 600px">
            <el-form :model="ruleForm" status-icon :rules="rules" label-position="left" ref="ruleForm"
                     label-width="100px" class="ruleForm">
              <el-form-item label="实验编号">
                <el-input size="medium" v-model="ruleForm.expid" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="功能单元编号">
                <el-input size="medium" v-model="ruleForm.unitid" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="功能单元名称">
                <el-input size="medium" v-model="ruleForm.unitname" :disabled="true"></el-input>
              </el-form-item>
              <el-row>
                <el-col span="50">
                  <el-form-item label="实验状态">
                    <el-select v-model="ruleForm.unitstate" placeholder="请选择" >
                      <el-option-group
                          v-for="group in options"
                          :key="group.label"
                          :label="group.label">
                        <el-option
                            v-for="item in group.options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                      </el-option-group>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="备注">
                <el-input
                    type="textarea"
                    :rows="3"
                    placeholder="备注"
                    maxlength="100"
                    show-word-limit
                    v-model="ruleForm.textarea">
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm()">提交</el-button>
              </el-form-item>
            </el-form>

          </div>

        </center>

      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {ElMessage} from "element-plus";
//import {ElMessageBox} from "element-plus";
import {ref} from 'vue'
import {get} from "@/utils/http";
//import moment from 'moment'

export default {
  name: "doLab",
  data() {
    return {
      newTime: '2021-7-17 18:12:00',
      timeOut: '',
      timeSave: '',
      timeer: '',
      timeDay: '',
      src: 'https://z3.ax1x.com/2021/07/17/Wl2fsJ.jpg',
      DataAccessSearch: {
        UnitName: '',
        ExpId: '',
        UnitId: '',
        StateIf: 0,
      },
      value1: true,
      options: [{
        label: '查验员',
        options: [{
          value: '资源不足',
          label: '资源不足'
        }, {
          value: '查验完成',
          label: '查验完成'
        }]
      }, {
        label: '独立PI',
        options: [{
          value: '实验失败',
          label: '实验失败'
        },]
      },
        {
          label: '科研助理',
          options: [{
            value: '数据有误',
            label: '数据有误'
          }, {
            value: '实验完成',
            label: '实验完成'
          }]
        }],
      ruleForm: {
        expid: '',
        unitid: '',
        unitname: '',
        unitstate: '',
        textarea: ref(''),
      },
      tableData: []
    };
  },
  created() {
    this.exp_id = this.$route.params.exp_id;
    this.pro_id = this.$route.params.pro_id;
    this.pro_name = this.$route.params.pro_name;
    this.pi_id = this.$route.params.pi_id;
    if (this.exp_id === undefined) {
      this.exp_id = sessionStorage.getItem("exp_id");
    } else {
      sessionStorage.setItem("exp_id", this.exp_id)
    }
    if (this.pro_id === undefined) {
      this.pro_id = sessionStorage.getItem("pro_id");
    } else {
      sessionStorage.setItem("pro_id", this.pro_id)
    }
    if (this.pro_name === undefined) {
      this.pro_name = sessionStorage.getItem("pro_name");
    } else {
      sessionStorage.setItem("pro_name", this.pro_name)
    }
    if (this.pi_id === undefined) {
      this.pi_id = sessionStorage.getItem("pi_id");
    } else {
      sessionStorage.setItem("pi_id", this.pi_id)
    }
    this.ruleForm.expid = this.exp_id;
    this.ruleForm.unitid = this.pro_id;
    this.ruleForm.unitname = this.pro_name;
  },
  methods: {
    setTime() {
      let that = this;
      Date.prototype.format = function (fmt) {
        var o = {
          "M+": this.getMonth() + 1,                 //月份
          "d+": this.getDate(),                    //日
          "h+": this.getHours(),                   //小时
          "m+": this.getMinutes(),                 //分
          "s+": this.getSeconds(),                 //秒
          "q+": Math.floor((this.getMonth() + 3) / 3), //季度
          "S": this.getMilliseconds()             //毫秒
        };

        if (/(y+)/.test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }

        for (var k in o) {
          if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(
                RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
          }
        }

        return fmt;
      }
      var now = new Date();
      var nowStr = now.format("yyyy-MM-dd hh:mm:ss");

      that.timeOut = setInterval(() => {
        let time_str = '';
        setTimeout(() => {
          //newtime是倒计时的结束时间，当前时间和newTime指定的时间相同时，倒计时为0，即倒计时结束
          get('/proPartialInfo/judge_authorization', {
            exp_id: that.exp_id,
            pro_id: that.pro_id,
            pi_id: that.pi_id,
            cur_time: nowStr
          }).then(function (aut) {
            let ed_time = aut.data[0].pro_end_time;
            time_str = ed_time.slice(0, 19);
            time_str = time_str.replace('T', ' ');
            console.log(time_str);
            let timedate = new Date(time_str);
            const now = new Date();
            const date = timedate.getTime() + 28800000 - now.getTime();
            console.log(date);
            const time = Math.ceil(date / 1000) % 60;
            const timeDay = Math.ceil(date / (1000 * 60)) - 1;
            that.timeer = time > 0 ? time : 0
            that.timeDay = timeDay > 0 ? timeDay : 0
          });

        }, 0)
      }, 1000)
    },
    handleClick(row) {
      let that = this;
      let router_target = 'updateData';
      //设置类似于console类型的功能
      if (row.procedurestate !== '实验完成') {
        that.$confirm("该实验尚未成功，是否获取其数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
            .then(() => {
              that.$router.push({
                name: router_target,
                params: {
                  exp_id: that.exp_id,
                  pro_id: that.pro_id,
                  pro_name: that.pro_name,
                  pi_id: that.pi_id,
                }
              })
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消数据访问"
              });
            });
      } else {
        that.$router.push({
          name: router_target
        })
      }
      console.log(row);
    },
    tableRowClassName({row}) {
      if (row.procedurestate === '实验完成') {
        return 'green-row';
      } else if (row.procedurestate === '归还完成' || row.procedurestate === '查验完成' || row.procedurestate === '申请完成') {
        return 'blue-row';
      } else if (row.procedurestate === '暂被撤销') {
        return 'gray-row';
      } else if (row.procedurestate === '尚未开始') {
        return 'white-row';
      }
      else {
        return 'red-row';
      }
    },
    onSubmit() {
      let that = this;
      let state = '';
      that.tableData = [];
      if (that.DataAccessSearch.ExpId.slice(0, 3) != 'EXP' && that.DataAccessSearch.ExpId != '') {
        ElMessage.warning({
          showClose: true,
          message: "实验编号应以EXP开头！",
          type: "warning",
          center: true
        })
      }
      if (that.DataAccessSearch.UnitId.slice(0, 2) != 'UN' && that.DataAccessSearch.UnitId != '') {
        ElMessage.warning({
          showClose: true,
          message: "功能单元编号应以UN开头！",
          type: "warning",
          center: true
        })
      }
      if(that.DataAccessSearch.UnitId == '' && that.DataAccessSearch.ExpId == '' && that.DataAccessSearch.UnitName == '' && that.DataAccessSearch.StateIf == false)
      {
        that.$notify({
          title: '提示',
          message: '您未选择查询条件，将为您呈现所有条目',
          type: 'warning',
          customClass: 'backgroundClass'
        });
      }
      if (that.DataAccessSearch.StateIf == true)
        state = '实验完成';
      get('/proPartialInfo/getInfo', {
        exp_id: that.DataAccessSearch.ExpId,
        pro_id: that.DataAccessSearch.UnitId,
        pro_name: that.DataAccessSearch.UnitName,
        pro_state: state
      }).then(function (res) {
            console.log(res.data);
            if (res.code === 1) {
              console.log(res.data);
              res.data.forEach(function (item) {
                var tmp = {
                  labid: item.exp_id,
                  procedureid: item.pro_id,
                  procedurename: item.pro_name,
                  procedurestate: item.pro_state
                };
                that.tableData.push(tmp);
              })
              return true;
            }
          }
      );
    },
    submitForm() {
      let that = this;
      console.log(that.ruleForm.unitstate);
      if (that.ruleForm.unitstate !== '实验失败') {
        ElMessage.warning({
          showClose: true,
          message: "您没有权限提交此类信息",
          type: "warning",
          center: true
        })
        return;
      } else {
        get('/proPartialInfo/updateState', {
          exp_id: that.ruleForm.expid,
          pro_id: that.ruleForm.unitid,
          pro_state: that.ruleForm.unitstate,
          other_info: that.ruleForm.textarea
        }).then(function (res) {
          if (res.code === 1) {
            ElMessage.success({
              showClose: true,
              message: "状态更新成功！",
              type: "success",
              center: true
            })
          } else {
            ElMessage.warning({
              showClose: true,
              message: "状态更新失败,未能找到相应记录!",
              type: "warning",
              center: true
            })
          }

        })

      }
    }
  }
}

</script>

<style>
.el-table .red-row {
  background: #FFDEDE;
}

.el-table .green-row {
  background: #C8FFCA;
}

.el-table .blue-row {
  background: #C8EAFB;
}

.el-table .white-row {
  background: #ffffff;
}

.el-table .grey-row {
  background: #cfd2d4;
}
.backgroundClass{
  background-color: #ffffff;
}
</style>